﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using TestUp.Models.Helpers;

namespace TestUp.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            if(User.Identity.IsAuthenticated)
                return RedirectToAction("PendingTests", "User");
            return View();
        }

        [HttpPost]
        public ActionResult LogIn(FormCollection formCollection)
        {
            string userName = formCollection["username"];
            string password = formCollection["password"];
            if(DataHelpers.UserInfoHelper.LogIn(userName, password))
            {
                var roles = DataHelpers.PermissionHelper.GetRoles(DataHelpers.UserInfoHelper.GetUserInfo(userName).Permission);

                var ticket = new FormsAuthenticationTicket(
                    1,
                    userName,
                    DateTime.Now,
                    DateTime.Now.AddMilliseconds(FormsAuthentication.Timeout.TotalMilliseconds),
                    false,
                    DataHelpers.PermissionHelper.ConvertToSingleRole(roles)
                );
                var encryptedTicket = FormsAuthentication.Encrypt(ticket);
                var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
                {
                    // IIRC this property is only available in .NET 4.0,
                    // so you might need a constant here to match the domain property
                    // in the <forms> tag of the web.config
                    Domain = FormsAuthentication.CookieDomain,
                    HttpOnly = true,
                    Secure = FormsAuthentication.RequireSSL,
                };
                Response.AppendCookie(authCookie);
                return RedirectToAction("PendingTests", "User");
            }
            ViewData.Add("error", "Check credentials and try again...");
            return View("Index");
        }

        public ActionResult LogOff()
        {
            DataHelpers.UserInfoHelper.LogOff(User.Identity.Name);

            if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
            {
                HttpCookie myCookie = new HttpCookie(FormsAuthentication.FormsCookieName);
                myCookie.Expires = DateTime.Now.AddDays(-1d);
                Response.Cookies.Add(myCookie);
            }

            return RedirectToAction("Index", "Home");
        }
    }
}
